// cso模块混入
import ElEditable from '@components/el-editable'
import SearchForm from '@components/businesscomponents/saas/search'
import { PAGE_NUMBER, PAGINATION_LAYOUT } from '@const/common'
import { cloneDeep } from 'lodash'
export default {
    components: {
      ElEditable,
      SearchForm
    },
    data() {
        return {
            //主页面
            mainPath: '/cso/serviceProvider',
            // 系统菜单列表
            statusButtons: {
                '1': ['提交', '编辑', '删除', '复制新增'],
                '2': ['复制新增', '通过', '驳回'],
                '3': ['复制新增', '通过', '驳回'],
                '4': ['编辑', '复制新增'],
                '5': ['复制新增'],
                '6': ['编辑', '复制新增'],

            },
            statusShowData: {
                '1': '待提交',
                '2': '待审核',
                '3': '审核通过',
                '4': '审核驳回',
                '5': '审计通过',
                '6': '审计驳回'
            },
            checkStatusData: {
                '0': '待审核',
                '1': '审核通过',
                '2': '审核驳回',
            },
            auditStatusData: {
                '0': '待审计',
                '1': '审计通过',
                '2': '审计驳回',
            },
            // 菜单表
            buttons: [],
            // 弹窗
            addProductDialogShow: false,
            // 选中货款行
            currentIndex: null,
            // 配送商
            distributorOptions: [],
            distributorLoading: false,
            // 开票单位
            purchaseCompanyNameList: [],
            // 采购单位
            invoiceCompanyNameList: [],
            // 服务商
            serviceProviderLoading: false,
            serviceProviderOptions: [],
            // 生产厂家
            manufacturerLoading: false,
            manufacturerOptions: [],
            // 搜索产品
            conditionjson: {},
            // 分页
            page:{
                curPage: 1,
                pageSize: PAGE_NUMBER[0],
                total: 0
            },
            listPage:{
                curPage: 1,
                pageSize: PAGE_NUMBER[0],
                total: 0
            },
            PAGE_NUMBER,
            PAGINATION_LAYOUT,
        }
    },
    mounted () {
        this.getButtons()
        if ('edit' in this.$route.query) {
            this.getDetailsById()
        }
    },
    computed: {
        //手动分页
        getTableData () {
            const data = this.formData[this.listName].filter((item, index) => {
            return index >= (this.listPage.curPage - 1) * this.listPage.pageSize && index < this.listPage.curPage * this.listPage.pageSize
            })
            this.listPage.total = this.formData[this.listName].length
            return data
        },
    },
    methods: {
        // 审核状态
        famaterStatus (val) {
            if (this.formData.status <= 2) {
                return  this.statusShowData[this.formData.status]
            } 
            if (this.formData.status <= 4) {
                return  this.checkStatusData[val]
            } else {
                return  this.auditStatusData[val]
            } 
        },
        // 过滤属性
        deleteOtherProps (data, fromData) {
            Object.keys(data).forEach(key => {
                if (!(key in fromData) && key !== 'id') {
                    delete data[key]
                }
            })
        },
        // 操作菜单分配
        async getButtons () {
            let buttonData = {
                type: 'btn',
                arr: [
                    { type: 'primary', val: '批量导入', handle: this.handleBatchImport },
                    {
                        type: 'text',
                        val: '下载导入模板.cvs',
                        handle: this.handleDownloadImportTemplate
                    },
                    { type: 'primary', val: '保存', handle: () => this.handleSave(this.initBody) },
                    { type: 'primary', val: '提交', handle: () => this.handleSubmission(this.initBody) },
                    { type: 'primary', val: '编辑', handle: () => this.handleEdit(this.initBody) },
                    { type: 'primary', val: '删除', handle: () => this.handleDelete() },
                    {
                        type: 'primary',
                        val: '复制新增',
                        handle: () => this.handleCopyAdd(this.initBody)
                    },
                    {
                        type: 'primary',
                        val: '保存并复制新增',
                        handle: () => this.handleSaveCopyAdd(this.initBody)
                    },
                    { type: 'primary', val: '通过', handle: this.handleAdopt },
                    {
                        type: 'primary',
                        val: '驳回',
                        handle: this.handleReject
                    }
                ]
            }
            let data = await this.filterButtons(cloneDeep(buttonData))
            this.$store.commit('changeLayoutHandle', data)
        },
        // 过滤菜单
        async filterButtons (data) {
            if (!this.addPage) {
                this.getDetails && await this.getDetails()
                // console.log(this.statusButtons[this.formData.status])
                this.buttons = this.buttons.filter(item => this.statusButtons[this.formData.status].includes(item))
            }
            const list = data.arr.filter(item => this.buttons.includes(item.val))
            data.arr = list
            return data
        },
        // 批量导入
        async handleBatchImport () {
            const valid = await this.$refs['formRules'].validate()
        },
        // 下载模板
        async handleDownloadImportTemplate () {
            await this.$axios.get(this.urlData.download)
            // window.open(this.urlData.download)
        },
        // 含税价计算
        multiplication (a, b) {
            return a * b
        },
         // 搜索功能-点击查询
        searchForm(condition) {
            this.page.curPage = 1
            this.conditionjson = condition
            this.getproductsList()
        },
        // 列表分页
        handleListSizeChange (pageSize) {
            this.listPage.pageSize = pageSize
        },
        // 列表分页
        handleListCurrentChange (page) {
            this.listPage.curPage = page
        },
        // 产品分页
        handleSizeChange(pageSize) {
            this.page.pageSize = pageSize
            this.getproductsList()
        },
        // 产品分页
        handleCurrentChange(curPage) {
            this.page.curPage = curPage
            this.getproductsList()
        },
        // 搜索功能-点击重置
        resetForm(condition) {
            this.page.curPage = curPage
            this.conditionjson = condition
        },
        // 处理index索引
        initIndex (listName) {
            this.formData[listName].forEach((item, index) => item.index = index + 1)
        },
        // 增加
        addTableRow (listName, data) {
            this.formData[listName].push(cloneDeep(data))
            if (this.formData[listName].length % this.listPage.pageSize === 1) {
                this.listPage.curPage ++
            }
            this.initIndex(listName)
        },
        // 删除
        deleteRow (index, listName) {
            if (this.formData[listName].length > 1) {
                if (index === this.formData[listName].length - 1 && this.formData[listName].length % this.listPage.pageSize === 1) {
                    this.listPage.curPage --
                }
                this.formData[listName].splice(index, 1)
                this.initIndex(listName)
            } else {
                this.$message.error('不能删除')
            }
        },
        // 复制
        copyAdd (row, listName) {
            this.formData[listName].push(cloneDeep(row))
            if (this.formData[listName].length % this.listPage.pageSize === 1) {
                this.listPage.curPage ++
            }
            this.initIndex(listName)
        },
        // 开票单位
        async getInvoiceCompanyNameList () {
            const data = await this.remoteList('FC')
            if (data) {
            this.invoiceCompanyNameList = this.downOptions(data)
            }
        },
        // 采购单位
        async getPurchaseCompanyNameList () {
            const data = await this.remoteList('HO')
            if (data) {
            this.purchaseCompanyNameList = this.downOptions(data)
            }
        },
        // 配送商
        async getManufacturerOptions () {
            const data = await this.remoteList('FC')
            if (data) {
            this.manufacturerOptions = this.downOptions(data)
            }
        },
        // 生产厂商
        async getDistributorOptionsList () {
            const data = await this.remoteList('AG')
            if (data) {
            this.distributorOptions = this.downOptions(data)
            }
        },
        // 处理下拉列表
        downOptions (data) {
            return data.map(item => {
                return {
                label: item.fullName,
                value: item.id
                }
            })
        },
        /** 
         * companyType | 请求类型
         * formItem | 表单绑定prop 暂时无用
         * 远程搜索请求
         */
        async remoteList (companyType, val = '') {
            const params = {
                companyType,
                // companyName: this.formData[formItem] // 现在不能模糊搜索
                companyName: ''
            }
            const { data, status } = await this.$axios.get(this.urlData.findCompany, {params})
            if (status === 200 && data.code === '0') {
                return data.payload || []
            }
        },
        //请求前置
        async beforeRequest (val) {
            return await this.$confirm(`确认要${val}吗`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'success'
            })
        },
        // 请求成功
        afterRequest (res, val, isOut = true, back) {
            if (res.code ==='0') {
                this.$message.success(`${val}成功`)
                back && back()
                if (isOut) {
                    console.log('router')
                    this.$router.push({
                        path: this.mainPath
                    })
                }
            } else {
                this.$message.error(`${res.msg}`)
            }
        },
        /**
         * 提交
         * @param {Function} init 处理数据
         * @param {Function | null} back 交互成功回调
         */
        async handleSubmission (init) {
            const valid = await this.$refs['formRules'].validate()
            if (valid) {
                const flag = await this.beforeRequest('提交')
                if (!flag) return
                const data = cloneDeep(this.formData)
                init(data)
                const res = await this.$axios.$post(this.urlData.submit, data)
                this.afterRequest(res, '提交')
            }
        },
        
        /**
         * 保存
         * @param {Function} init 处理数据
         * @param {Function | null} back 交互成功回调
         */
        async handleSave (init) {
            const valid = await this.$refs['formRules'].validate()
            if (valid) {
                const flag = await this.beforeRequest('保存')
                if (!flag) return
                const data = cloneDeep(this.formData)
                init(data)
                const res = await this.$axios.$post(this.urlData.add, data)
                this.afterRequest(res, '保存')
            }
        },
        /**
         * 保存并复制新增
         * @param {Function} init 处理数据
         * @param {Function | null} back 交互成功回调
         */
        async handleSaveCopyAdd (init) {
            const valid = await this.$refs['formRules'].validate()
            if (valid) {
                const flag = await this.beforeRequest('保存')
                if (!flag) return
                const data = cloneDeep(this.formData)
                init(data)
                const res = await this.$axios.$post(this.urlData.add, data)
                this.afterRequest(res, '保存', false)
            }
        },
         /**
         * 保存并复制新增
         * @param {Function} init 处理数据
         * @param {Function | null} back 交互成功回调
         */
        async handleDelete () {
            const flag = await this.beforeRequest('删除')
            if (!flag) return
            const data = cloneDeep(this.formData)
            const params = {
                voucherId: this.formData.id
            }
            const res = await this.$axios.$delete(this.urlData.del, { params })
            this.afterRequest(res, '删除')
        },
        // 通过id查询
        async getDetailsById () {
            const { checkListName, listName } = this
            const params = {
                voucherId: this.$route.query.id
            }
            const res = await this.$axios.$get(this.urlData.check, { params })
            this.afterRequest(res, '获取', false, () => {
                this.formData = res.payload
                this.formData[listName] = this.formData[checkListName]
                delete this.formData[checkListName]
            })
        },
        // 复制新增
        handleCopyAdd (init) {
            this.$router.push({
                path: this.editPath,
                query: {
                    id: this.formData.id,
                    edit: false
                }
            })
        },
        // 驳回
        handleReject(){
            this.dialogFormRejectVisible = true;
        },
        // 通过
        handleAdopt(){
            this.dialogFormVisible = true;
            this.auditingCompanyList = this.remoteList ('AG')
        },
        // 审核
        handleDistributor(status){
            const data = {
                id: this.$route.query.id,
                status: status,
                entrustCompanyId: this.form.id || "",//审计公司ID （非必传，配送商审核时选择了就传）
                entrustCompanyName:this.form.region || "",//审计公司名称 （非必传，配送商审核时选择了就传）
                [this.sendName]: this.formData[this.listName],
                reason: this.rejectForm.region || ""//（审核驳回时必填）
            }
            this.$axios.$post(this.urlData.submit, data).then(res=>{
                if (!Number(res.code)) {
                    if(status === 3){
                        this.$message.success('审核通过成功')
                    }else{
                        this.$message.success('审核驳回成功')
                    }
                    this.$router.push({
                        path: this.mainPath
                    })
                }
            })
        },
        // 审计
        handleAudit(status){
            const data = {
                id: this.$route.query.id,
                status: status,
                entrustCompanyId: this.$store.state.companyId,//审计公司ID （非必传，配送商审核时选择了就传）
                entrustCompanyName: this.$store.state.companyName || "",//审计公司名称 （非必传，配送商审核时选择了就传）
                [this.sendName]: this.formData[this.listName],
                reason: this.rejectForm.region || ""//（审计驳回时必填）
            }
            this.$axios.$post(this.urlData.submit, data).then(res=>{
                if (!Number(res.code)) {
                    if(status === 5){
                        this.$message.success('审核通过成功')
                    }else{
                        this.$message.success('审核驳回成功')
                    }
                    this.$router.push({
                        path: this.mainPath
                    })
                }
            })
        }      
    }
  }